package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        Integer page = params.getPage();
        Integer size = params.getSize();
        //1.创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        try {
            //构建查询条件
            buildBasicQuery(request, params);

            //设置分页参数
            request.source().from((page - 1) * size);
            request.source().size(size);

            //2.调用客户端执行请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("查询出现错误   {}", e.getMessage());
            return null;
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        //1.创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        //设置搜索条件
        buildBasicQuery(request, params);
        //size 0
        request.source().size(0);
        //指定 city分租 starName分组 brand分组
        buildAggsRequest(request);
        //执行请求
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //解析相应结果
            Aggregations aggregations = response.getAggregations();
            //获取city分组聚合结果
            List<String> cityList = handleAggsResult(aggregations, "city");
            //获取starName分组聚合结果
            List<String> starNameList = handleAggsResult(aggregations, "starName");
            //获取brand分组聚合结果
            List<String> brandList = handleAggsResult(aggregations, "brand");
            HashMap<String, List<String>> map = new HashMap<>();
            map.put("city", cityList);
            map.put("starName", cityList);
            map.put("brand", cityList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("服务出现异常 {}", e.getMessage());
            return null;
        }
    }

    @Override
    public List<String> suggestion(String key) {
        //创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        //创建自动补全请求
        request.source().suggest(
                new SuggestBuilder()
                        .addSuggestion("mySuggestion",
                                SuggestBuilders.completionSuggestion("suggestion")
                                        .prefix(key)
                                        .skipDuplicates(true)
                                        .size(10)
                        ));
        //执行
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //解析响应
            Suggest suggest = response.getSuggest();
            //查询自定义的结果
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
            //获取结果中的options并遍历取出每个option的text
            ArrayList<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                list.add(option.getText().toString());
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("自动提升查询失败, {} ", e.getMessage());
            return null;
        }
    }

    private List<String> handleAggsResult(Aggregations aggregations, String name) {
        Terms result = aggregations.get("city");
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = result.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    private void buildAggsRequest(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("city").field("city").size(20));
        request.source().aggregation(AggregationBuilders.terms("starName").field("starName").size(20));
        request.source().aggregation(AggregationBuilders.terms("brand").field("brand").size(20));
    }

    private void buildBasicQuery(SearchRequest request, RequestParams params) {
        String key = params.getKey();

        /**
         * 查询关键字条件
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(key)) {
            //查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            //match 查询all字段
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        /**
         * 查询城市
         */
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }

        /**
         * 查询品牌
         */
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        /**
         * 查询星级
         */
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }

        /**
         * 查询价格范围
         */
        Integer minPrice = params.getMinPrice();
        if (minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }

        /**
         * 查询价格范围
         */
        Integer maxPrice = params.getMaxPrice();
        if (maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lt(maxPrice));
        }


        String location = params.getLocation();
        if (StringUtils.isNotBlank(location)) {
            request.source().sort( //设置排序
                    SortBuilders.geoDistanceSort("location", new GeoPoint(location)) //按照地理坐标 排序
                            .order(SortOrder.ASC) //升序
                            .unit(DistanceUnit.KILOMETERS) // 距离单位 KM
            );

        }

        /**
         * 增加算分查询条件
         */
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )

                }
        );
        //设置条件
        request.source().query(boolQuery);
    }

    /**
     * 解析相应结果
     *
     * @param response
     * @return
     */
    private PageResult handleResponse(SearchResponse response) {
        //命中结果
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] docArr = hits.getHits();
        ArrayList<HotelDoc> list = new ArrayList<>();
        for (SearchHit doc : docArr) {

            HotelDoc hotelDoc = JSON.parseObject(doc.getSourceAsString(), HotelDoc.class);

            //将排序的值 存入到distance字段中 用于前端页面显示中
            Object[] sortValues = doc.getSortValues();
            if (sortValues != null && sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }
            list.add(hotelDoc);
        }
        return new PageResult(total, list);
    }
}
